//
//  ViewController.swift
//  pgy
//
//  Created by vsccw on 2018/12/28.
//  Copyright © 2018 vsccw.com. All rights reserved.
//

import UIKit

import RxSwift
import RxCocoa
import NSObject_Rx
import SDWebImage

class ViewController: UITableViewController {
  
  let items = BehaviorRelay<[AppInfo]>(value: [])
  
  override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.title = "QwikMatch"
    tableView.delegate = nil
    tableView.dataSource = nil
    tableView.estimatedRowHeight = 44
    tableView.register(UINib(nibName: AppInfoCell.identifier, bundle: nil), forCellReuseIdentifier: AppInfoCell.identifier)
    
    items.asObservable().bind(to: tableView.rx.items(cellIdentifier: AppInfoCell.identifier, cellType: AppInfoCell.self)) { (index, item, cell) in
      cell.info = item
    }
    .disposed(by: rx.disposeBag)
    
    tableView.rx.itemSelected.asObservable()
      .subscribe(onNext: { [weak self] (indexPath) in
        self?.tableView.deselectRow(at: indexPath, animated: true)
      }).disposed(by: rx.disposeBag)
    
    tableView.rx.modelSelected(AppInfo.self).subscribe(onNext: { (app) in
      Application.shared.install(app)
    }).disposed(by: rx.disposeBag)
    
    API.shared.provider.rx
      .request(.listMyPublish(1, .iOS))
      .retry(2)
      .map(ListMyPublish.self, atKeyPath: nil, using: JSONDecoder(), failsOnEmptyData: false)
      .debug()
      .asObservable()
      .map({ $0.data?.apps ?? [] })
      .catchErrorJustReturn([])
      .bind(to: items)
      .disposed(by: rx.disposeBag)
  }
  
  
}

